package com.heyun.interceptor;

import com.heyun.utils.JwtUtil;
import com.heyun.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Value("heyun")
    private String SecretKey;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String uri = request.getRequestURI();
//        System.out.println(uri);
//        if (uri.contains("/permission/login") || uri.contains("/student/download")) {
//            System.out.println("Skipping interceptor for path: " + uri);
//            return true;
//        }
        String token = request.getHeader("Authorization");
        //验证token
        try {
            //放行
            Map<String, Object> claims = JwtUtil.parseToken(SecretKey, token);
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            //http响应状态码为401
            response.setStatus(401);
            // 重定向到登录界面
//            response.setHeader("Location", "/");
            //不放行
            return false;
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
